import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, asyncRouterMap } from '@/config/router.config'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from 'store'
import store from '@/store'
import NProgress from 'nprogress' // progress bar

Vue.use(Router)

NProgress.configure({ showSpinner: false })

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// console.log(constantRouterMap.concat(asyncRouterMap))

const router = new Router({
  mode: 'history',
  routes: constantRouterMap
})


const loginRoutePath = '/user/login'

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (storage.get(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
      next('/')
    } else {
      if (store.getters.addRouters.length === 0) {
        store.dispatch('GetInfo').then(res => {
          const menus = res.data.menus
          store.dispatch('GenerateRoutes', menus).then(() => {
            store.getters.addRouters.forEach(r => {
              router.addRoute(r)
            })
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              next({ ...to, replace: true })
            } else {
              next({ path: redirect })
            }
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (to.path === loginRoutePath) {
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done()
    }
  }
})


router.afterEach(() => {
  NProgress.done() // finish progress bar
})


export default router
